import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:schoollifedemo/base/common_function.dart';
import 'package:schoollifedemo/business/personal/viewmodel/personal_info_edit_page_viewmodel.dart';
import 'package:schoollifedemo/commonwidget/button_widget.dart';
import 'package:schoollifedemo/commonwidget/circle_empty_widget.dart';
import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/common_dialog.dart';
import 'package:schoollifedemo/commonwidget/error_widget.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget_with_overflow.dart';
import 'package:schoollifedemo/commonwidget/textfield_widget.dart';
import 'package:schoollifedemo/entity/Entity.dart';

class PersonalInfoEditPage extends BaseStatefulPage {
  const PersonalInfoEditPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _PersonalInfoEditPageState();
  }
}

class _PersonalInfoEditPageState extends BasePageState<PersonalInfoEditPage> {
  final PersonalInfoEditPageViewModel _viewModel =
      PersonalInfoEditPageViewModel();

  final Color _defaultColor = const Color(0xFFD0E7FF);
  final Color _selectColor = const Color(0xFF88B5FA);

  final Color _backgroundColor = const Color(0x66D0E7FF);
  bool _isEdit = false;

  @override
  void initState() {
    _viewModel.init();
    _viewModel.pullAllSchoolInfo(onFailure: (msg) {
      DialogUtils.showSimpleDialog(
        context,
        clickOutSideDismiss: true,
        title: '错误',
        widgets: Padding(
          padding: const EdgeInsets.only(left: 10, right: 10),
          child: TextWidgetWithOverflow(
            msg,
            fontSize: 16,
          ),
        ),
      );
    });
    _viewModel.pullPersonalInfo(onFailure: (msg) {
      DialogUtils.showSimpleDialog(
        context,
        clickOutSideDismiss: true,
        title: '错误',
        widgets: Padding(
          padding: const EdgeInsets.only(left: 10, right: 10),
          child: TextWidgetWithOverflow(
            msg,
            fontSize: 16,
          ),
        ),
      );
    });
    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: StreamBuilder(
          stream: _viewModel.loadingState,
          initialData: CommonLoadingState.loading,
          builder: (buildContext, snapshot) {
            CommonLoadingState? loadingState =
                snapshot.data as CommonLoadingState?;
            switch (loadingState) {
              case CommonLoadingState.loading:
                return Container(
                  child: const LoadingWidget(),
                  color: Colors.white,
                );
              case CommonLoadingState.successTypeOne:
              case CommonLoadingState.successTypeTwo:
                return _bodyWidget();
              case CommonLoadingState.failure:
              default:
                return Container(
                  color: Colors.white,
                  child: const CommonErrorWidget('错误'),
                );
            }
          },
        ),
      ),
    );
  }

  // 取消修改按钮
  Widget _cancelButton(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 30),
      child: ButtonWidget(
        insideWidget: Image.asset('assets/images/common/icon_cancel.png'),
        width: 80,
        height: 50,
        radius: 50,
        disableColor: const Color(0x55E85252),
        enableColor: const Color(0xFFE85252),
        onButtonClick: () async {
          if (_isEdit) {
            bool? trueOrFalse = await DialogUtils.showCancelAndConfirmDialog(
              context,
              title: '提示',
              msg: '已更改信息，是否取消修改?',
            );
            if (trueOrFalse == true) {
              // 取消更改时直接回退
              _viewModel.backPage(context);
            }
          } else {
            _viewModel.backPage(context);
          }
        },
      ),
    );
  }

  // 确认修改按钮
  Widget _confirmButton(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 30),
      child: ButtonWidget(
        insideWidget: Image.asset('assets/images/common/img_arrow_right.png'),
        width: 80,
        height: 50,
        radius: 50,
        onButtonClick: () async {
          if (_isEdit) {
            bool? trueOrFalse = await DialogUtils.showCancelAndConfirmDialog(
              context,
              title: '提示',
              msg: '确定修改信息?',
            );
            if (trueOrFalse == true) {
              // 确定修改信息:
              String? resultMessage =
                  await _viewModel.sureToChangePersonalInfo();
              if (resultMessage == null) {
                // 修改信息成功后返回页面
                _viewModel.backPage(context);
              } else {
                DialogUtils.showTitleAndMessageDialog(
                  context,
                  title: '错误',
                  msg: resultMessage,
                  clickOutSideDismiss: true,
                );
              }
            }
          }
        },
      ),
    );
  }

  Widget _bodyWidget() {
    return Container(
      color: Colors.white,
      child: ListView(
        physics: const BouncingScrollPhysics(),
        children: [
          Row(
            children: [
              GestureDetector(
                onTap: () async {
                  if (_isEdit) {
                    bool? trueOrFalse =
                        await DialogUtils.showCancelAndConfirmDialog(
                      context,
                      title: '提示',
                      msg: '已更改信息，是否取消修改?',
                    );
                    if (trueOrFalse == true) {
                      // 取消更改时直接回退
                      _viewModel.backPage(context);
                    }
                  } else {
                    _viewModel.backPage(context);
                  }
                },
                child: Container(
                  margin: const EdgeInsets.only(left: 20),
                  child: const Icon(Icons.arrow_back_ios_outlined),
                ),
              ),
              const Expanded(
                child: TextWidgetWithOverflow(
                  '个人信息修改页面',
                  fontSize: 28,
                  insideColor: Colors.transparent,
                  textAlign: TextAlign.left,
                ),
              ),
            ],
          ),
          Padding(
            padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
            child: CircleEmptyWidget(
                Column(
                  children: [
                    _editIconAndNicknameWidget(),
                    _editPersonalIntroduceWidget(),
                    _editSexWidget(),
                    GestureDetector(
                      onTap: () async {
                        DialogUtils.showSimpleCupertinoDialog(
                          context,
                          title: '选择你的学校',
                          widgets: _schoolShowList(),
                          clickOutSideDismiss: true,
                        );
                      },
                      child: _editOtherWidget(
                        title: '学校',
                        currentValue: _viewModel
                            .getPersonalInfoResponse()
                            ?.school
                            ?.schoolName,
                        editable: false,
                      ),
                    ),
                    _editOtherWidget(
                      title: '地区',
                      currentValue: _viewModel.getPersonalInfoResponse()?.area,
                      editable: true,
                      onTextChange: (text) {
                        String? oldArea =
                            _viewModel.getPersonalInfoResponse()?.area;
                        if (text != oldArea) {
                          _isEdit = true;
                          _viewModel.setNewArea(text);
                        }
                      },
                    ),
                    _editOtherWidget(
                      title: '手机号码',
                      currentValue: _viewModel.getPersonalInfoResponse()?.phone,
                      editable: true,
                      maxLength: 13,
                      onTextChange: (text) {
                        String? oldPhone =
                            _viewModel.getPersonalInfoResponse()?.phone;
                        if (text != oldPhone) {
                          _isEdit = true;
                          _viewModel.setNewPhone(text);
                        }
                      },
                    ),
                    _editOtherWidget(
                      title: '学号',
                      currentValue:
                          _viewModel.getPersonalInfoResponse()?.studentId,
                      editable: true,
                      onTextChange: (text) {
                        String? oldStudentId =
                            _viewModel.getPersonalInfoResponse()?.studentId;
                        if (text != oldStudentId) {
                          _isEdit = true;
                          _viewModel.setNewStudentId(text);
                        }
                      },
                    ),
                    Offstage(
                      offstage:
                          _viewModel.getPersonalInfoResponse()?.teacherId ==
                              null,
                      child: _editOtherWidget(
                        title: '教师ID',
                        currentValue:
                            _viewModel.getPersonalInfoResponse()?.teacherId,
                        editable: false,
                      ),
                    ),
                    Offstage(
                      offstage:
                          _viewModel.getPersonalInfoResponse()?.teacherId ==
                              null,
                      child: _editOtherWidget(
                        title: '所教课程',
                        currentValue:
                            _viewModel.getPersonalInfoResponse()?.teachClass,
                        editable: true,
                        onTextChange: (text) {
                          String? oldTeachClass =
                              _viewModel.getPersonalInfoResponse()?.teachClass;
                          if (text != oldTeachClass) {
                            _isEdit = true;
                            _viewModel.setNewTeachClass(text);
                          }
                        },
                      ),
                    ),
                    Offstage(
                      offstage: _viewModel
                              .getPersonalInfoResponse()
                              ?.administratorId ==
                          null,
                      child: _editOtherWidget(
                        title: '管理ID',
                        currentValue: _viewModel
                            .getPersonalInfoResponse()
                            ?.administratorId,
                        editable: false,
                      ),
                    ),
                  ],
                ),
                insideColor: _backgroundColor),
          ),
          Padding(
            padding: const EdgeInsets.only(bottom: 30),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [_cancelButton(context), _confirmButton(context)],
            ),
          )
        ],
      ),
    );
  }

  Widget _editIconAndNicknameWidget() {
    return Container(
      margin: const EdgeInsets.only(left: 10, right: 10, top: 20, bottom: 10),
      child: Row(
        children: [
          SizedBox(
            width: 68,
            height: 68,
            child: GestureDetector(
              child: ClipOval(
                child: Image.network(
                  _viewModel.getIconAddress(),
                ),
              ),
              onTap: () async {
                // 跳转到头像选择界面
                await _viewModel.turnToSelectIconPage(context);
                _viewModel.pullPersonalInfo(
                  onFailure: (msg) {
                    DialogUtils.showSimpleDialog(
                      context,
                      clickOutSideDismiss: true,
                      title: '错误',
                      widgets: Padding(
                        padding: const EdgeInsets.only(left: 10, right: 10),
                        child: TextWidgetWithOverflow(
                          msg,
                          fontSize: 16,
                        ),
                      ),
                    );
                  },
                );
                _isEdit = true;
              },
            ),
          ),
          Expanded(
            child: Container(
              margin: const EdgeInsets.only(left: 5, right: 5),
              child: CircleEmptyWidget(
                Container(
                  margin: const EdgeInsets.only(
                    left: 5,
                    right: 5,
                    bottom: 5,
                    top: 10,
                  ),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          const TextWidgetWithOverflow(
                            '你的账号:',
                            textAlign: TextAlign.left,
                            fontSize: 16,
                            width: 90,
                            insideColor: Colors.transparent,
                          ),
                          Expanded(
                            child: TextWidgetWithOverflow(
                              _viewModel.getPersonalInfoResponse()?.account,
                              textAlign: TextAlign.left,
                              insideColor: Colors.transparent,
                              fontSize: 16,
                            ),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          const TextWidgetWithOverflow(
                            '你的昵称:',
                            textAlign: TextAlign.left,
                            fontSize: 16,
                            width: 90,
                            insideColor: Colors.transparent,
                          ),
                          Expanded(
                            child: TextFieldWidget(
                              initText: _viewModel
                                  .getPersonalInfoResponse()
                                  ?.nickname,
                              cursorColor: Colors.black,
                              fontSize: 16,
                              textColor: Colors.black,
                              insideColor: Colors.transparent,
                              maxLength: 20,
                              onTextChange: (text) {
                                String? oldNickname = _viewModel
                                    .getPersonalInfoResponse()
                                    ?.nickname;
                                if (oldNickname == text) {
                                  // 没有更改内容，无需更改
                                } else {
                                  _viewModel.setNickname(text);
                                  _isEdit = true;
                                }
                              },
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _editPersonalIntroduceWidget() {
    return Container(
      margin: const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 10),
      child: CircleEmptyWidget(
        Column(
          children: [
            Container(
              padding: const EdgeInsets.only(left: 5, top: 10, right: 5),
              child: const TextWidgetWithOverflow(
                '你的描述：',
                insideColor: Colors.transparent,
                fontSize: 16,
                textAlign: TextAlign.left,
                width: double.infinity,
              ),
            ),
            Container(
              margin: const EdgeInsets.only(bottom: 10),
              child: TextFieldWidget(
                initText: _viewModel.getPersonalInfoResponse()?.personalProfile,
                insideColor: Colors.transparent,
                fontSize: 16,
                textAlign: TextAlign.left,
                textColor: Colors.black,
                cursorColor: Colors.black,
                width: double.infinity,
                keyboardType: TextInputType.multiline,
                maxLine: 8,
                enableCountText: true,
                maxLength: 100,
                onTextChange: (text) {
                  _isEdit = true;
                  _viewModel.setPersonalIntroduce(text);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _editSexWidget() {
    return Container(
      margin: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
      child: Row(
        children: [
          Expanded(
            child: CircleEmptyWidget(
              Row(
                children: [
                  const Expanded(
                    child: TextWidgetWithOverflow(
                      '性别:',
                      fontSize: 16,
                      insideColor: Colors.transparent,
                    ),
                  ),
                  Expanded(
                    child: TextWidgetWithOverflow(
                      _viewModel.getUserSex(),
                      fontSize: 16,
                      insideColor: Colors.transparent,
                    ),
                  ),
                ],
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              _viewModel.setNewSex(1);
              _isEdit = true;
              setState(() {});
            },
            child: Container(
              margin: const EdgeInsets.only(left: 4, right: 2),
              child: CircleEmptyWidget(
                TextWidgetWithOverflow(
                  '男',
                  fontSize: 16,
                  insideColor: _viewModel.getPersonalInfoResponse()?.sex == 1
                      ? _selectColor
                      : _defaultColor,
                ),
                width: 50,
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              _viewModel.setNewSex(0);
              _isEdit = true;
              setState(() {});
            },
            child: Container(
              margin: const EdgeInsets.only(left: 2, right: 2),
              child: CircleEmptyWidget(
                TextWidgetWithOverflow(
                  '女',
                  fontSize: 16,
                  insideColor: _viewModel.getPersonalInfoResponse()?.sex == 0
                      ? _selectColor
                      : _defaultColor,
                ),
                width: 50,
              ),
            ),
          ),
          GestureDetector(
            onTap: () {
              _viewModel.setNewSex(3);
              _isEdit = true;
              setState(() {});
            },
            child: Container(
              margin: const EdgeInsets.only(left: 2),
              child: CircleEmptyWidget(
                TextWidgetWithOverflow(
                  '保密',
                  fontSize: 16,
                  insideColor: _viewModel.getPersonalInfoResponse()?.sex != 1 &&
                          _viewModel.getPersonalInfoResponse()?.sex != 0
                      ? _selectColor
                      : _defaultColor,
                ),
                width: 60,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _schoolShowList() {
    return SizedBox(
      width: 100,
      height: 200,
      child: ListView.separated(
        physics: const BouncingScrollPhysics(),
        itemCount: _viewModel.getAllSchoolResponse()?.schoolList?.length ?? 0,
        itemBuilder: (context, index) {
          final schoolInfo =
              _viewModel.getAllSchoolResponse()?.schoolList?[index];
          return GestureDetector(
            onTap: () {
              _viewModel.setNewSchool(schoolInfo!);
              Navigator.pop(context);
              setState(() {});
            },
            child: Padding(
              padding: const EdgeInsets.only(left: 10, right: 10),
              child: TextWidgetWithOverflow(
                _viewModel
                    .getAllSchoolResponse()
                    ?.schoolList?[index]
                    ?.schoolName,
                fontSize: 16,
              ),
            ),
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          return const SizedBox(
            height: 10,
          );
        },
      ),
    );
  }

  Widget _editOtherWidget({
    required String title,
    required currentValue,
    bool editable = false,
    int? maxLength,
    OnTextChange? onTextChange,
  }) {
    return Padding(
      padding: const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5),
      child: CircleEmptyWidget(
        Row(
          children: [
            TextWidgetWithOverflow(
              title,
              fontSize: 14,
              insideColor: Colors.transparent,
              width: 80,
            ),
            Expanded(
              child: CircleEmptyWidget(
                !editable
                    ? TextWidgetWithOverflow(
                        currentValue,
                        fontSize: 14,
                      )
                    : TextFieldWidget(
                        initText: currentValue,
                        fontSize: 14,
                        textColor: Colors.black,
                        cursorColor: Colors.black,
                        insideColor: _defaultColor,
                        maxLength: maxLength,
                        onTextChange: onTextChange,
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
